package cn.tedu.coolshark.filter;


import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//配置拦截的请求路径
@WebFilter(filterName = "MyFilter",urlPatterns = {"/insertProduct.html","/admin.html"})
public class MyFilter implements Filter {
    //当过滤器初始化时执行的方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    //当接受到请求时,会执行此方法,需要在此方法中进行判断,是否允许访问Controller或静态资源文件
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将父类型转换为子类型
        HttpServletRequest st = (HttpServletRequest) servletRequest;
        HttpServletResponse se = (HttpServletResponse) servletResponse;
        //得到会话对象
        HttpSession session = st.getSession();
        //从会话对象中得到登录成功时保存的用户对象
        User user = (User) session.getAttribute("user");
        if (user != null) { //代表登录过
            filterChain.doFilter(servletRequest,servletResponse); //表示放行,允许访问资源
        }else { //代表未登录
            se.sendRedirect("/login.html"); //重定向,让客户端重新向指定的地址发出请求
        }
        System.out.println("过滤器执行了!");
    }

    //当过滤器销毁时执行的方法
    @Override
    public void destroy() {
    }
}
